package club.banyuan;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.Socket;
import java.util.Arrays;
import java.util.Scanner;

public class DownloadClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new
                Socket("127.0.0.1", 5000);
        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();

        // 读取服务器传过来的文件数量
        int num = ByteToInt.toInt(getBytes(inputStream, 4));

        // 读取服务器传过来的文件名和文件长度
        FileInfo[] fileInfos = new FileInfo[num];
        for (int i = 0; i < num; i++) {
            byte[] lenBytes = getBytes(inputStream, 4);
            int jsonLen = ByteToInt.toInt(lenBytes);

            byte[] jsonBytes = getBytes(inputStream, jsonLen);
            fileInfos[i] = JSONObject.parseObject(jsonBytes, FileInfo.class);
            System.out.println((i+1) + "." + fileInfos[i]);
        }


        // 选择下载的文件
        Scanner scanner = new Scanner(System.in);
        int choose ;
        while (true) {
            System.out.println("请输入要下载的文件编号");
            choose = scanner.nextInt();
            if (choose != 1 && choose != 2 && choose != 3 && choose != 4) {
                System.out.println("输入不合法，请重新输入");
            } else {
                outputStream.write(ByteToInt.toBytes(choose));
                break;
            }
        }

        byte[] buf = new byte[1024];
        long fileLeft = fileInfos[choose-1].getLength();
        File file = new File("/Users/edz/banyuan/Java/20.Socket/practice/03.FileServer/src","Refine"+fileInfos[choose-1].getName());
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));

        int read = inputStream.read(buf, 0, (int) Math.min(fileLeft, buf.length));
        while (fileLeft>0){
            bufferedOutputStream.write(buf,0,read);
            fileLeft-=read;
            read = inputStream.read(buf,0,(int) Math.min(fileLeft, buf.length));
        }
        bufferedOutputStream.close();
        socket.close();
    }


    private static byte[] getBytes(InputStream inputStream, int total) throws IOException {
        byte[] lengthBytes = new byte[total];
        int len = inputStream.read(lengthBytes);
        if (len != lengthBytes.length) {
            throw new IllegalArgumentException("读取长度错误");
        }
        return lengthBytes;
    }
}
